package org.jground.rx.ui.zk.viewControl;

import java.math.BigDecimal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.codetable.Codetable;
import org.jground.codetable.DefaultCodetable;
import org.jground.codetable.DefaultCodetableElement;
import org.jground.rx.RXSystem;
import org.jground.rx.RXView;
import org.jground.rx.ui.zk.UIFrame;
import org.jground.util.ArrayUtils;
import org.jground.util.L;
import org.jground.util.StringUtils;
import org.jground.zk.zulX.ComboboxX;
import org.jground.zk.zulX.HboxX;
import org.zkoss.zul.Decimalbox;

public class UIAttributeControlCurrency extends UIAttributeControlBase {

    public static String CURRENCY_CODETABLE_NAME = "currencies";

    private static Log logger = LogFactory.getLog(UIAttributeControlCurrency.class);

    public UIAttributeControlCurrency createNew(UIFrame uiFrame, RXView moControl) {
        return new UIAttributeControlCurrency(uiFrame, moControl);
    }

    //

    private Decimalbox amountDb;
    private ComboboxX codeTableUI;

    public UIAttributeControlCurrency() {}

    private UIAttributeControlCurrency(UIFrame uiFrame, RXView moControl) {
        super(uiFrame, moControl);
        L.debug(logger, "codetable name", CURRENCY_CODETABLE_NAME);
        Codetable ct;
        try {
            ct = RXSystem.getInstance().getCtService().getCodetable(CURRENCY_CODETABLE_NAME, true);
        } catch (Exception e) {
            ct = new DefaultCodetable(CURRENCY_CODETABLE_NAME, e.toString(), new DefaultCodetableElement("--", e
                    .toString()));
        }
        codeTableUI = new ComboboxX(ct);
        codeTableUI.setReadonly(true);
        codeTableUI.setMaxlength(4);
        codeTableUI.setWidth("50px");
        // codeTableUI.setModel(codeTableModel = new CodeTableListModel(ct));
        amountDb = new Decimalbox();
        add(new HboxX(amountDb, codeTableUI));
    }

    public void set(String... values) {
        clear();
        if (ArrayUtils.isNotEmpty(values)) {
            try {
                String amount = values[0];
                String code = values[1];
                codeTableUI.setSelected(code);
                amountDb.setValue(new BigDecimal(amount));
            } catch (Exception e) {
                logger.warn(e, e);
            }
        }
    }

    public String[] get() {
        String code = codeTableUI.getSelected();
        String amount = amountDb.getValue() == null ? "" : amountDb.getValue().toString();
        return code == null ? StringUtils.EMPTY_STRING_ARRAY : ArrayUtils.toArray(amount, code);
    }

    public void clear() {
        if (codeTableUI.getItemCount() > 0) {
            codeTableUI.setSelectedIndex(0);
            amountDb.setValue("0");
        }
    }

}